package com.yangzhe.algorithm.c010;

import java.util.Random;

public class MergeTwoLists {
    protected static class ListNode {
        public int val;

        public ListNode next;

        public ListNode(int i) {
            val = i;
        }
    }


    public static void main(String[] args) {
        // 生成两个随机链表
        ListNode list1 = generateSortedLinkedList(5);
        ListNode list2 = generateSortedLinkedList(5);

        // 打印链表1
        System.out.println("链表1:");
        printLinkedList(list1);

        // 打印链表2
        System.out.println("\n链表2:");
        printLinkedList(list2);

        System.out.println("\n合并链表:");
        printLinkedList(mergeTwoLists(list1, list2));
    }


    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }

        if (list2 == null) {
            return list1;
        }

        ListNode resultHead = null;
        ListNode current1 = null;
        ListNode current2 = null;
        if (list1.val < list2.val) {
            resultHead = list1;
            current1 = list1.next;
            current2 = list2;
        } else {
            resultHead = list2;
            current1 = list1;
            current2 = list2.next;
        }

        ListNode pre = resultHead;
        while (current1 != null && current2 != null) {
            if (current1.val < current2.val) {
                pre.next = current1;
                current1 = current1.next;
            } else {
                pre.next = current2;
                current2 = current2.next;
            }
            pre = pre.next;
        }
        pre.next = current1 == null ? current2 : current1;
        return resultHead;
    }


    // 生成包含n个节点的升序链表
    public static ListNode generateSortedLinkedList(int n) {
        if (n <= 0) return null;

        Random random = new Random();
        int currentValue = random.nextInt(10); // 初始值0-9
        ListNode head = new ListNode(currentValue);
        ListNode current = head;

        for (int i = 1; i < n; i++) {
            // 确保下一个值比当前值大（随机增量1-10）
            currentValue += random.nextInt(10) + 1;
            current.next = new ListNode(currentValue);
            current = current.next;
        }


        return head;
    }

    // 打印链表
    public static void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val);
            if (current.next != null) {
                System.out.print(" -> ");
            }
            current = current.next;
        }
        System.out.println();
    }


}
